package medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * TODO 894. 所有可能的真二叉树
 * 创建时间：2024-04-02 09:02
 * 地址：https://leetcode.cn/problems/all-possible-full-binary-trees/description/
 */
public class 所有可能的真二叉树_894 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    static class Solution {
        public List<TreeNode> allPossibleFBT(int n) {

            // 真二叉树，节点数为奇数
            if (n % 2 == 0) {
                return new ArrayList<>();
            }
            // 节点数为1时，直接返回
            else if (n == 1) {
                return Collections.singletonList(new TreeNode(0));
            } else {
                int l = (n + 1) / 2; // 叶子节点个数
                List<TreeNode>[] nodes = new ArrayList[11];
                Arrays.setAll(nodes, o -> new ArrayList<>());
                // nodes[i] 为有 i 个叶子的所有真二叉树的列表
                nodes[1].add(new TreeNode());
                for (int i = 2; i < nodes.length; i++) { // 计算f[i]
                    for (int j = 1; j < i; j++) { // 枚举左子树的叶子节点
                        for (TreeNode left : nodes[j]) {
                            for (TreeNode right : nodes[i - j]) {
                                nodes[i].add(new TreeNode(0, left, right));
                            }
                        }
                    }
                }
                return nodes[l];
            }
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.allPossibleFBT(7));

    }
}
